package de.baumann.browser.utils

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import de.baumann.browser.utils.FileUtil
import java.io.ByteArrayOutputStream
import java.io.File

class BitmapUtil {

    /**
     * 拍照
     *
     * @param context
     * @param fileName
     * @param requestCode
     */
    fun takepictures(context: Context, fileName: String): Intent {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getUri(context, fileName))
        return intent
    }

    private fun getUri(context: Context, fileName: String): Uri {
        val file = FileUtil.creatFile(fileName, FileUtil.FILE_TYPE_IMAGES)
        val imageUri: Uri

        imageUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            getUri(context, file)
        } else {
            getOutUri(fileName)
        }
        return imageUri
    }

    private fun getUri(context: Context, file: File): Uri {
        return FileProvider.getUriForFile(context, context.packageName + ".fileprovider", file)
    }

    private fun getOutUri(fileName: String): Uri {
        val file = FileUtil.creatFile(fileName, FileUtil.FILE_TYPE_IMAGES)
        val imageUri: Uri
        imageUri = Uri.fromFile(file)
        return imageUri
    }

    fun photoCrop(context: Context, uri: Uri?, type: Int, fileName: String, path: String, aspectX: Int, aspectY: Int, outputX: Int, outputY: Int): Intent {
        val intent = Intent("com.android.camera.action.CROP")
        if (type == 1000) {
            intent.setDataAndType(getUri(context, File(path)), "image/*")
        } else {
            intent.setDataAndType(uri, "image/*")
        }

        // 设置裁剪
        intent.putExtra("crop", "true")
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", aspectX)
        intent.putExtra("aspectY", aspectY)
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", outputX)
        intent.putExtra("outputY", outputY)
        intent.putExtra("scale", true)
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
        //人脸识别 默认为true
        intent.putExtra("noFaceDetection", true)
        intent.putExtra("return-data", false)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getOutUri(fileName))
        return intent
    }
}